package com.lemon.api.auto.ApiExecutor;

import com.alibaba.fastjson.JSONObject;
import com.lemon.api.auto.util.PropertiesUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/*

字符串转换成list
*/
public class ApiExecutor {
    public static List<NameValuePair> paramStringToParamList(String paramString) {
        List<NameValuePair> paramters=new ArrayList<NameValuePair>();
        //将json格式的字符串解析成MAP
        Map<String,String> jsonMap = (Map<String, String>) JSONObject.parse(paramString);
        //从map中取出所有的key（参数名）
        Set<String> paramNames = jsonMap.keySet();
        //循环处理每一个参数名，取出参数值，再封成NameValuePair类型的对象
        for (String paramName : paramNames) {
            String paramValue = jsonMap.get(paramName);
            paramters.add(new BasicNameValuePair(paramName,paramValue));
        }
        return paramters;
    }
    public static void doService(String url, String type, String paramString) {
        //拿到配置的接口类型
        String charset ="UTF-8";
        String contentType= PropertiesUtil.properties.getProperty("api.content.type");
        //以“表单”格式提交的接口
        if ("form".equalsIgnoreCase(contentType)) {
            //将满足json格式的字符串解析成参数列表
            List<NameValuePair> paramters = ApiExecutor.paramStringToParamList(paramString);
            if("post".equalsIgnoreCase(type)){
                FromSubmitApiExecutor.doPost(url,paramters,charset);
            }else if ("get".equalsIgnoreCase(type)){
                FromSubmitApiExecutor.doGet(url,paramters,charset);
            }
            //以json格式提交接口
        }else if ("json".equalsIgnoreCase(type)){
            if ("post".equalsIgnoreCase(type)){
                JsonSubmitApiExecutor.doPost(url,paramString,charset);
            }else if ("get".equalsIgnoreCase(type)){
                JsonSubmitApiExecutor.doGet(url,paramString,charset);
            }
        }
    }
}
